<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>加油卡管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="所属公司">
              <a-select
                class="selectInputWidth"
                show-search
                allowClear
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                :not-found-content="null"
                v-model="searchForm.custId"
                @search="handleNameChange"
              >
                <a-select-option v-for="d in nameLikeData" :key="d.id">{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="加油卡">
              <a-select
                class="selectInputWidth"
                show-search
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                allowClear
                :not-found-content="null"
                v-model="searchForm.cardId"
                @search="handleOilCardChange"
              >
                <a-select-option v-for="d in oilCardLikeData" :key="d.cardId">{{ d.cardNo }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="车牌号">
              <a-input v-model="searchForm.truckNumber" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model="searchForm.status" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="1">正常</a-select-option>
                <a-select-option :key="0">冻结</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleCreate">+ 创建加油卡</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出excel</a-button>
            </a-form-item>
          </a-form>

          <a-table
            :columns="columns"
            :data-source="tableData"
            :loading="loading"
            class="tableMargin"
            :pagination="pagination"
            rowKey="cardId"
            :scroll="{x: 1366}"
            @change="handleTableChange"
          >
            <template slot="rn" slot-scope="text, record, index">
              {{index + 1}}
              <span class="redMsg" v-if="checkAccount(record.amount)">余额不足</span>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a
                @click="freezeIt(record)"
              >{{record.status === 1 ? '冻结': (record.status === 0 ? '恢复':'')}}</a>
              <a @click="viewIt(record.cardId, record.cardNo)">明细</a>
              <a
                v-if="record.status === 0 && record.rechargeAmount === 0 && record.usedAmount === 0"
                @click="deleteIt(record.cardId)"
              >删除</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 创建加油卡 -->
    <a-modal
      :visible="visible"
      title="创建加油卡"
      centered
      destroyOnClose
      :maskClosable="false"
      :confirmLoading="confirmLoading"
      @ok="handleAdd"
      @cancel="handleCancel"
    >
      <a-row>
        <a-col :span="23">
          <a-form-model
            ref="rulesForm"
            :model="form"
            :rules="formRules"
            :label-col="{span:6}"
            :wrapper-col="{span:16}"
          >
            <a-form-model-item label="类型">
              <a-radio-group v-model="businessType">
                <a-radio :value="1">中石化</a-radio>
                <a-radio :value="2">中石油</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="所属公司" prop="custId">
              <a-select
                show-search
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                :not-found-content="null"
                v-model="form.custId"
                @search="handleNameChangeModal"
                @select="emptyChange"
              >
                <a-select-option v-for="d in nameLikeDataModal" :key="d.id">{{ d.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="卡号" prop="cardNo">
              <a-input v-model="form.cardNo" :max-length="maxLength" />
            </a-form-model-item>
            <a-form-model-item label="车牌号" prop="truckId">
              <a-select
                show-search
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                :not-found-content="null"
                v-model="form.truckId"
                @search="handleCarNameChange"
                @select="emptyChange2"
              >
                <a-select-option v-for="d in carLikeData" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 恢复加油卡 -->
    <a-modal
      :visible="visible2"
      title="恢复加油卡"
      centered
      destroyOnClose
      :maskClosable="false"
      @ok="handleOk2"
      @cancel="handleCancel2"
    >
      <a-form-model
        ref="rulesFormModal"
        :model="form2"
        :rules="formRules2"
        :label-col="{span:6}"
        :wrapper-col="{span:16}"
      >
        <a-form-model-item label="类型">{{item.type === 1 ? '中石化' : '中石油'}}</a-form-model-item>
        <a-form-model-item label="所属公司">{{item.custName}}</a-form-model-item>
        <a-form-model-item label="卡号">{{item.cardNo}}</a-form-model-item>
        <a-form-model-item label="车牌号" prop="truckId">
          <a-select
            show-search
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            v-model="form2.truckId"
            @search="handleCarNameChange"
            @select="emptyChange2"
          >
            <a-select-option v-for="d in carLikeData2" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { commonExport } from '@/api/request'
import { queryCustNameList, queryTruckOilCardDown } from '@/api'
import { queryTruckOilCardList, addTruckOilCard, updateTruckOilCardStatus, queryNoCardTruckNumberDown, deleteTruckOilCard } from '@/api/landCenter'

const fomrMessage = `必填项不能为空`
const defaultCreateForm = () => ({
  custId: '',
  truckId: '',
  cardNo: ''
})

export default {
  data () {
    this.handleNameChange = debounce(this.handleNameChange, 800)
    this.handleNameChangeModal = debounce(this.handleNameChangeModal, 800)
    this.handleCarNameChange = debounce(this.handleCarNameChange, 800)
    this.handleOilCardChange = debounce(this.handleOilCardChange, 800)
    return {
      loading: false,
      confirmLoading: false,
      businessType: 1,
      carLikeData: [],
      carLikeData2: [],
      nameLikeData: [],
      nameLikeDataModal: [],
      oilCardLikeData: [],
      searchForm: {
        status: '',
        cardId: null,
        custId: null,
        truckNumber: '',
        sort: null
      },
      columns: [
        {
          title: '序号',
          width: 60,
          scopedSlots: { customRender: 'rn' }
        },
        {
          title: '加油卡',
          dataIndex: 'cardNo'
        },
        {
          title: '类型',
          dataIndex: 'type',
          width: 80,
          customRender: (text) => {
            if (text === 1) {
              return '中石化'
            } else if (text === 2) {
              return '中石油'
            }
          },
          _needName: true
        },
        {
          title: '所属公司',
          dataIndex: 'custName'
        },
        {
          title: '车牌号',
          dataIndex: 'truckNumber'
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '100px',
          customRender: (text, row, index) => {
            if (text === 1) {
              return <a-badge status="success" text="正常" />
            } else if (text === 0) {
              return <a-badge status="error" text="冻结" />
            }
          },
          _needName: true
        },
        {
          title: '当前余额(元)',
          dataIndex: 'amount',
          sorter: true
        },
        {
          title: '充值总金额（元）',
          dataIndex: 'rechargeAmount'
        },
        {
          title: '消费总金额（元）',
          dataIndex: 'usedAmount'
        },
        {
          title: '操作',
          width: '120px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // modal
      visible: false,
      form: defaultCreateForm(),
      formRules: {
        custId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        cardNo: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        truckId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      },
      // 恢复
      visible2: false,
      item: {},
      form2: {
        truckId: ''
      },
      formRules2: {
        truckId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      }
    }
  },
  computed: {
    maxLength () {
      return this.businessType === 1 ? 19 : 16
    }
  },
  watch: {
    businessType () {
      this.form.cardNo = ''
    }
  },
  methods: {
    checkAccount (v) { // 余额≤1000的情况下，加油卡记录需要打上“余额不足”的标签
      const account = parseFloat(v)
      return account <= 1000
    },
    handleOilCardChange (nameLike) { // 加油卡
      if (nameLike) {
        queryTruckOilCardDown({
          word: nameLike
        }).then(rsp => {
          this.oilCardLikeData = rsp.data
        })
      } else {
        this.oilCardLikeData = []
      }
    },
    handleNameChange (nameLike = '') { // 陆运应付结算对象
      if (nameLike) {
        queryCustNameList({
          nameLike,
          belongCompany: 'JIA_TE',
          custTypeLike: 'SUPPLIER',
          status: 1,
          isPayable: 1
        }).then(rsp => {
          this.nameLikeData = rsp.data
        })
      } else {
        this.nameLikeData = []
      }
    },
    handleNameChangeModal (nameLike = '') { // 陆运应付结算对象modal
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_TE',
        custTypeLike: 'SUPPLIER',
        status: 1,
        isPayable: 1
      }).then(rsp => {
        this.nameLikeDataModal = rsp.data
      })
    },
    emptyChange (e) {
      this.handleNameChangeModal()
    },
    handleCarNameChange (nameLike = '') {
      queryNoCardTruckNumberDown({
        word: nameLike
      }).then(rsp => {
        this.carLikeData = rsp.data
        this.carLikeData2 = rsp.data
      })
    },
    emptyChange2 (e) {
      this.handleCarNameChange()
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      queryTruckOilCardList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      }).catch(() => { this.loading = false })
    },
    handleTableChange (pagination, filters, sorter) {
      if (sorter.order === 'ascend') {
        this.searchForm.sort = '0'
      } else if (sorter.order === 'descend') {
        this.searchForm.sort = '1'
      } else {
        this.searchForm.sort = null
      }
      this.handleSubmit()
    },
    exportExcel () {
      commonExport('/truckStock/exportTruckOilCardList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    },
    handleCreate () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }

      this.handleNameChangeModal() //  初始化车辆
      this.handleCarNameChange() // 初始化车牌

      this.form = defaultCreateForm()
      this.businessType = 1
      this.carLikeData = []
      if (this.$refs.rulesForm) {
        this.$refs.rulesForm.resetFields()
      }
      this.visible = true
    },
    handleAdd () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          addTruckOilCard({ ...this.form, type: this.businessType }).then(rsp => {
            this.$message.success('创建成功')
            this.handleCancel()
            this.handleSubmit()
            setTimeout(() => { this.confirmLoading = false }, 1000)
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    viewIt (id, cardNo) {
      this.$router.push({ path: 'fuelCardManagement/' + id, query: { cardNo } })
    },
    freezeIt (item) {
      if (!this.$root._bc.frozen) {
        this.$message.error('您无此权限！')
        return
      }
      const isFrozen = item.status
      let text = '确定冻结吗？'
      let successText = '冻结成功！'
      if (isFrozen === 0) {
        // text = '确定恢复正常吗？'
        // successText = '恢复成功！'
        this.item = { ...item }
        this.form2.truckId = ''
        this.visible2 = true
        this.handleCarNameChange()
        return false
      }

      let _this = this
      this.$confirm({
        title: text,
        okType: 'danger',
        onOk () {
          updateTruckOilCardStatus({ cardId: item.cardId, status: 1 - isFrozen }).then(rsp => {
            _this.$message.success(successText)
            _this.handleSubmit()
          })
        }
      })
    },
    handleOk2 () {
      this.$refs.rulesFormModal.validate(valid => {
        if (valid) {
          updateTruckOilCardStatus({ cardId: this.item.cardId, status: 1 - this.item.status, truckId: this.form2.truckId }).then(rsp => {
            this.visible2 = false
            this.$message.success('恢复成功！')
            this.handleSubmit()
          })
        }
      })
    },
    handleCancel2 () {
      this.visible2 = false
      this.carLikeData2 = []
    },
    deleteIt (cardId) {
      deleteTruckOilCard({ cardId }).then(rsp => {
        this.$message.success('删除成功')
        this.handleSubmit()
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.handleSubmit()
    })
  }
}
</script>

<style lang="less" scoped>
/deep/ td {
  position: relative;
  .redMsg {
    position: absolute;
    display: inline-block;
    background: red;
    top: 0;
    width: 60px;
    left: 0;
    font-size: 12px;
    height: 16px;
    text-align: center;
    color: white;
  }
}
</style>
